package org.jeecg.modules.demo.weixin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class WeixinAuth {


    private static final String GET_ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    //APPIDSECRET

    public static String getAccessToken(String appId, String appSecret) throws Exception {
//        String url = String.format(GET_ACCESS_TOKEN_URL, appId, appSecret);

        String _appId="wxbd1bed9021faaae4";
        String _appSecret="e6ac6db9b2bc7cfb2785d81ac144ec90";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + _appId +
                "&secret=" + _appSecret + "&code=CODE&grant_type=authorization_code";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求属性
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 200
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON获取access_token
            String accessToken = parseAccessTokenFromJson(response.toString());
            return accessToken;
        } else {
            throw new Exception("Error while fetching access token. Response Code: " + responseCode);
        }
    }

    private static String parseAccessTokenFromJson(String jsonStr) {
        // 这里使用简单的字符串操作来获取access_token，实际上应该使用JSON解析库如Jackson或Gson
        int start = jsonStr.indexOf("\"access_token\":\"") + 15;
        int end = jsonStr.indexOf("\"", start);
        return jsonStr.substring(start, end);
    }
}
